//
//  HZAmotionCell.swift
//  weibo002
//
//  Created by 黑眼圈 on 16/4/27.
//  Copyright © 2016年 heiyan. All rights reserved.
//

import UIKit

class HZAmotionCell: UICollectionViewCell {
    
  
    
    
    var indexPath:NSIndexPath?{
        
        didSet{
            

            label.hidden = (indexPath?.section != 0)
            
            
        }
        
        
    }
    
    var amotioArr:[HZEmotionModel]?{
        
        didSet{
            
            //如果没有数据就直接返回
            guard let arr = amotioArr else {
                return
            }
            
        
            for value in btnArr {
                //默认隐藏
                value.hidden = true
            }
            
     
            //遍历数据赋值
            for (index,value) in arr.enumerate() {
                
                
                let btn = btnArr[index]
                
                //赋值了之后就显示
                btn.hidden = false
                
                //赋值给自定义按钮,让它自己判断显示内容
               btn.value = value
                
            }
            
            
            
        }
        
    }
    
    
    
    lazy var btnArr:[HZAmotionBtn] = [HZAmotionBtn]()
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        
        backgroundColor = UIColor.whiteColor()
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //添加子控件
    private func setupUI(){
        
        //添加20个按钮
        setupBtn()
        
        
        contentView.addSubview(label)
        contentView.addSubview(deleteBtn)
        
        
        //约束
        label.snp_makeConstraints { (make) -> Void in
            
            make.bottom.equalTo(contentView.snp_bottom).offset(-10)
            make.centerX.equalTo(contentView)
        }
        
        
        //添加长按手势
        let longGesture = UILongPressGestureRecognizer(target: self, action: "longGestureImg:")
        
        //添加上去
        contentView.addGestureRecognizer(longGesture)
        
    }
    
    
    // MARK: -  实现长按手势方法
    @objc private func longGestureImg(gesture:UILongPressGestureRecognizer){

        //获取点击的点
        let point = gesture.locationInView(gesture.view)
        
        var btn:HZAmotionBtn?
        
        //变量所有按钮
        for button in btnArr {
            
            // 如果点在某个按钮的范围内
            if CGRectContainsPoint(button.frame, point) {
                
                // 记录这个按钮
                btn = button
                break
            }
        }
        
        //开始长按和长按改变时调用
        if gesture.state == .Changed || gesture.state == .Began {
            
            
            //获取最上面一个 window
            let window = UIApplication.sharedApplication().windows.last!
            
            //赋值
            popView.btn.value = btn!.value
            
            //转换坐标
            let ract = btn!.convertRect(btn!.bounds, toView: window)
            
            popView.center.x = CGRectGetMidX(ract)
            popView.frame.origin.y = CGRectGetMaxY(ract)-popView.frame.height
            
            
            window.addSubview(popView)
            

            
        } else {
            //其他情况移除
            popView.removeFromSuperview()
        }
        
        
    

        
    }
    
    //添加20个按钮
    private func setupBtn(){
        
        for _ in 0..<20 {
            
            let btn = HZAmotionBtn()
            
            //监听按钮点击
            btn.addTarget(self, action: "insertImg:", forControlEvents: .TouchUpInside)
            
            btn.titleLabel?.font = UIFont.systemFontOfSize(30)
            
            //添加上去
            contentView.addSubview(btn)
            
            btnArr.append(btn)
        }
        
    }
    
    
    // MARK: -  实现表情按钮的点击事件
    @objc private func insertImg(btn:HZAmotionBtn){
        
        //保存到最近表情的数组中
        HZEmotionVM.sharedEmotion.saveImgData(btn.value!)
        
        
        //获取最上面一个 window
        let window = UIApplication.sharedApplication().windows.last!
        
        //赋值
        popView.btn.value = btn.value
        
        //转换坐标
        let ract = btn.convertRect(btn.bounds, toView: window)
        
        popView.center.x = CGRectGetMidX(ract)
        popView.frame.origin.y = CGRectGetMaxY(ract)-popView.frame.height
        
        
        window.addSubview(popView)
        
        //显示之后要消失
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.25 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            
            self.popView.removeFromSuperview()
        }
        
        
        //发布通知
        NSNotificationCenter.defaultCenter().postNotificationName("img", object: btn)
        
    }
    
    
    // MARK: -  布局时调用
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let w = self.bounds.size.width/7
        let h = (self.bounds.size.height-25)/3
        
        var row:Int?
        var column:Int?
        
        for (inde,value) in btnArr.enumerate() {
            
            row = inde/7
            column = inde%7
    
            value.frame = CGRect(x: CGFloat(column!)*w, y: CGFloat(row!)*h, width: w, height: h)
        }
        
        //设置删除按钮的位置
        let x = contentView.frame.size.width-w
        let y = contentView.frame.size.height-h-25
        
        
        deleteBtn.frame = CGRect(x: x, y: y, width: w, height: h)
        
    }
    
    
    // MARK: -  懒加载控件
    lazy var label:UILabel = {
        
       let label = UILabel()
        
        label.textColor = UIColor.darkGrayColor()
        label.text = "最近使用的表情"
        label.font = UIFont.systemFontOfSize(14)
        
        return label
    }()
    
    lazy var deleteBtn:UIButton = {
        
       let btn = UIButton()
        
        //监听按钮点击事件
        btn.addTarget(self, action: "didDelete", forControlEvents: .TouchUpInside)
        
        btn.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: .Highlighted)
        btn.setImage(UIImage(named: "compose_emotion_delete"), forState: .Normal)

       
        return btn
    }()
    
    
    
    lazy var popView:HZAmotionPopView = {
        
       let popView = HZAmotionPopView.popView()
        
        return popView
    }()
    
    
    // MARK: -  监听取消按钮点击事件
    @objc private func didDelete(){
        
        //发布通知
        NSNotificationCenter.defaultCenter().postNotificationName("delete", object: self)
    }
    
    
}
